import {defineStore} from "pinia";
import {ref, computed} from "vue";
import type {AccessToken} from "@/api/login/types";

/**
 * 组合式的方式
 * state    ref的数据
 * actions 修改数据 普通方法
 * getters 获取数据 计算属性
 */
export const useTokenStore = defineStore('token', () => {
    /* state */
    const token = ref<AccessToken>({
        username: '',
        accessToken: ''
    })

    /* 设置token */
    const setToken = (tokenObj: AccessToken) => {
        token.value = tokenObj
    }

    /* 清空token */
    const clearToken = () => {
        token.value = {
            username: '',
            accessToken: ''
        }
    }

    const username = computed(() => token.value.username)
    const accessToken = computed(() => token.value.accessToken)

    return {token, setToken, clearToken, username, accessToken}
}, {
    persist: {
        key: 'tokenStore',
        storage: sessionStorage
    }
})